import { importFromOrigin } from './common.js'
import { getDomList, getHooks } from './formatFile.js'

export const formatData = (str) => {
  if (!str) return ''
  importFromOrigin('ref')
  const formattedStr = str.replace(/data.*?\n.*?return/g, '').replace(/\}$/g, '')
  // to do 如果data里面有不规范的写法 比如this.getOSSImage('XXX'), new Function会报错
  const obj = new Function('return ' + formattedStr)()
  const formattedData = Object.entries(obj)
    .map(([key, val]) => {
      return `const ${key} = ref(${JSON.stringify(val)})`
    })
    .join('\n')
  const domList = getDomList()
  const domsRefs = domList.map((dom) => `const ${dom} = ref()`).join('\n')
  const hooks = getHooks()
  const hooksDefine = hooks.map((item) => `const ${item.name} = ${item.method}()`).join('\n')

  return `${hooksDefine}
  ${formattedData}
  ${domsRefs}
      `
}
